extends Control
const Item_listing = preload("res://2d/item_listing.tscn")

signal closed
signal item_selected(item)


export(bool) var close_on_select = true
export(bool) var select_nothing_on_close = true
export(bool) var add_nothing_to_list = true

onready var items = $VBoxContainer/HBoxContainer2/Panel/VBoxContainer/items
onready var details_name = $VBoxContainer/HBoxContainer2/Panel2/item_details/name
onready var details_description = $VBoxContainer/HBoxContainer2/Panel2/item_details/description
onready var details_icon = $VBoxContainer/HBoxContainer2/Panel2/item_details/icon_big

func _ready():
	pass # Replace with function body.

func open(inventory):
	if add_nothing_to_list:
		var listing = Item_listing.instance()
		listing.set_item(null)
		listing.connect("pressed", self, "on_selected", [null])
		listing.connect("focus_entered", self, "on_item_focused", [null])
		items.add_child(listing)
	
	for key in inventory.items.keys():
		var item = inventory.items[key]
		var listing = Item_listing.instance()
		listing.set_item(item)
		listing.connect("pressed", self, "on_selected", [item])
		listing.connect("focus_entered", self, "on_item_focused", [item])
		items.add_child(listing)
	if items.get_child_count() > 0:
		items.get_child(0).grab_focus()
	self.visible = true
	$AnimationPlayer.play("open")
	
func close():
	self.queue_free()

func focus_listing():
	if items.get_child_count() > 0:
		items.get_child(0).grab_focus()

func on_selected(item):
	emit_signal("item_selected", item)
	if close_on_select:
		self.close()

func on_item_focused(item):
	if not item:
		details_name.text = "Nothing"
		details_description.text = ""
		details_icon.texture = null
		return
	details_name.text = item.definition.full_name()
	details_description.text = item.definition.description
	details_icon.texture = item.definition.icon()

func _process(delta):
	if Input.is_action_just_pressed("ui_cancel"):
		if select_nothing_on_close:
			on_selected(null)
		else:
			self.close()
